﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Xml;
using System.Text;
using System.Xml.Linq;
using System.Linq;


/// <summary>
/// XML 操作基类
/// </summary>
public class CoXmlHelper
{


    #region 有关获取的操作
    public static int GetIntConfigValue(string key, string fileName)
    {
        if (string.IsNullOrEmpty(key))
            throw new ArgumentNullException("获取配置信息(" + key + "),原因：传入的key为空!");
        string xmlPath = AppDomain.CurrentDomain.BaseDirectory + @"Configs\";
        if (string.IsNullOrEmpty(fileName))
            xmlPath += "SiteInfo";
        else
            xmlPath += fileName;
        xmlPath += ".config";

        int value = 0;
        try
        {
            XDocument xml = xml = XDocument.Load(xmlPath);
            var configs = xml.Element("configuration").Element("appSettings");
            string temp = (from p in configs.Elements("add") where p.Attribute("key").Value == key select p).First().Attribute("value").Value.ToString();

            if (!int.TryParse(temp, out value))
                throw new ArithmeticException("获取配置信息(" + key + "),原因：转型失敗!");
        }
        catch (Exception ex)
        {

            throw new ArgumentException("获取配置信息(" + key + "),原因：" + ex.Message);

        }
        return value;
    }
    public static double GetDoubleConfigValue(string key, string fileName)
    {

        if (string.IsNullOrEmpty(key))
            throw new ArgumentNullException("获取配置信息(" + key + "),原因：传入的key为空!");
        string xmlPath = AppDomain.CurrentDomain.BaseDirectory + @"Configs\";
        if (string.IsNullOrEmpty(fileName))
            xmlPath += "SiteInfo";
        else
            xmlPath += fileName;
        xmlPath += ".config";

        double value = 0;
        try
        {
            XDocument xml = xml = XDocument.Load(xmlPath);
            var configs = xml.Element("configuration").Element("appSettings");
            string temp = (from p in configs.Elements("add") where p.Attribute("key").Value == key select p).First().Attribute("value").Value.ToString();



            if (!double.TryParse(temp, out value))
                throw new ArithmeticException("获取配置信息(" + key + "),原因：转型失敗!");
        }
        catch (Exception ex)
        {

            throw new ArgumentException("获取配置信息(" + key + "),原因：" + ex.Message);

        }
        return value;
    }
    public static string GetStringConfigValue(string key, string fileName)
    {

        if (string.IsNullOrEmpty(key))
            throw new ArgumentNullException("获取配置信息(" + key + "),原因：传入的key为空!");
        string xmlPath = AppDomain.CurrentDomain.BaseDirectory + @"Configs\";
        if (string.IsNullOrEmpty(fileName))
            xmlPath += "SiteInfo";
        else
            xmlPath += fileName;
        xmlPath += ".config";
        var value = "";
        try
        {
            XDocument xml = xml = XDocument.Load(xmlPath);
            var configs = xml.Element("configuration").Element("appSettings");
            value = (from p in configs.Elements("add") where p.Attribute("key").Value == key select p).First().Attribute("value").Value.ToString();
        }
        catch (Exception ex)
        {

            throw new ArgumentException("获取配置信息(" + key + "),原因：" + ex.Message);

        }
        return value;
    }
    public static bool GetBoolConfigValue(string key, string fileName)
    {

        if (string.IsNullOrEmpty(key))
            throw new ArgumentNullException("获取配置信息(" + key + "),原因：传入的key为空!");
        string xmlPath = AppDomain.CurrentDomain.BaseDirectory + @"Configs\";
        if (string.IsNullOrEmpty(fileName))
            xmlPath += "SiteInfo";
        else
            xmlPath += fileName;
        xmlPath += ".config";

        bool value = false;
        try
        {
            XDocument xml = xml = XDocument.Load(xmlPath);
            var configs = xml.Element("configuration").Element("appSettings");
            var temp = (from p in configs.Elements("add") where p.Attribute("key").Value == key select p).First().Attribute("value").Value.ToString();


            if (!bool.TryParse(temp, out value))
                throw new ArithmeticException("获取配置信息(" + key + "),原因：转型失敗!");

        }
        catch (Exception ex)
        {

            throw new ArgumentException("获取配置信息(" + key + "),原因：" + ex.Message + "!");

        }
        return value;
    }
    #endregion
    #region 有关获取的操作
    /// <summary>
    /// 根据Key在配置文件中返回Int类型的数据
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public static int GetIntConfigValue(string key)
    {
        if (string.IsNullOrEmpty(key))
            throw new ArgumentNullException("获取配置信息(" + key + "),原因：传入的key为空!");
        string xmlPath = AppDomain.CurrentDomain.BaseDirectory + @"Configs\SiteInfo.config";

        int value = 0;
        try
        {
            XDocument xml = xml = XDocument.Load(xmlPath);
            var configs = xml.Element("configuration").Element("appSettings");
            string temp = (from p in configs.Elements("add") where p.Attribute("key").Value == key select p).First().Attribute("value").Value.ToString();

            if (!int.TryParse(temp, out value))
                throw new ArithmeticException("获取配置信息(" + key + "),原因：转型失敗!");
        }
        catch (Exception ex)
        {

            throw new ArgumentException("获取配置信息(" + key + "),原因：" + ex.Message);

        }
        return value;
    }
    public static double GetDoubleConfigValue(string key)
    {

        if (string.IsNullOrEmpty(key))
            throw new ArgumentNullException("获取配置信息(" + key + "),原因：传入的key为空!");
        string xmlPath = AppDomain.CurrentDomain.BaseDirectory + @"Configs\SiteInfo.config";

        double value = 0;
        try
        {
            XDocument xml = xml = XDocument.Load(xmlPath);
            var configs = xml.Element("configuration").Element("appSettings");
            string temp = (from p in configs.Elements("add") where p.Attribute("key").Value == key select p).First().Attribute("value").Value.ToString();



            if (!double.TryParse(temp, out value))
                throw new ArithmeticException("获取配置信息(" + key + "),原因：转型失敗!");
        }
        catch (Exception ex)
        {

            throw new ArgumentException("获取配置信息(" + key + "),原因：" + ex.Message);

        }
        return value;
    }
    public static string GetStringConfigValue(string key)
    {

        if (string.IsNullOrEmpty(key))
            throw new ArgumentNullException("获取配置信息(" + key + "),原因：传入的key为空!");
        string xmlPath = AppDomain.CurrentDomain.BaseDirectory + @"Configs\SiteInfo.config";
        var value = "";
        try
        {
            XDocument xml = xml = XDocument.Load(xmlPath);
            var configs = xml.Element("configuration").Element("appSettings");
            value = (from p in configs.Elements("add") where p.Attribute("key").Value == key select p).First().Attribute("value").Value.ToString();
        }
        catch (Exception ex)
        {

            return "";
            throw new ArgumentException("获取配置信息(" + key + "),原因：" + ex.Message);


        }
        return value;
    }

    public static string GetStringConfigSValue(string key, string xmlName)
    {

        if (string.IsNullOrEmpty(key))
            throw new ArgumentNullException("获取配置信息(" + key + "),原因：传入的key为空!");
        string xmlPath = AppDomain.CurrentDomain.BaseDirectory + @"Configs\" + xmlName;
        var value = "";
        try
        {
            XDocument xml = XDocument.Load(xmlPath);
            var configs = xml.Element("configuration").Element("appSettings");
            value = (from p in configs.Elements("add") where p.Attribute("key").Value == key select p).First().Attribute("value").Value.ToString();
        }
        catch (Exception ex)
        {

            throw new ArgumentException("获取配置信息(" + key + "),原因：" + ex.Message);

        }
        return value;
    }


    public static ListItemCollection GetStringListValue(string xmlName)
    {
        ListItemCollection map = new ListItemCollection();
        string xmlPath = AppDomain.CurrentDomain.BaseDirectory + @"Configs\" + xmlName;
        try
        {
            XDocument xml = XDocument.Load(xmlPath);
            //  XElement configs = ;
            foreach (var p in xml.Element("configuration").Element("appSettings").Elements("add"))
            {
                map.Add(new ListItem(p.Attribute("key").Value, p.Attribute("value").Value));
            }
            /*
            ListItem li = new ListItem(de.Key.ToString(), de.Value.ToString());
            map.Add(li);*/

        }
        catch (Exception ex)
        {

            throw new ArgumentException("获取配置信息(" + xmlName + "),原因：" + ex.Message);

        }

        return map;
    }


    public static bool GetBoolConfigValue(string key)
    {

        if (string.IsNullOrEmpty(key))
            throw new ArgumentNullException("获取配置信息(" + key + "),原因：传入的key为空!");
        string xmlPath = AppDomain.CurrentDomain.BaseDirectory + @"Configs\SiteInfo.config";

        bool value = false;
        try
        {
            XDocument xml = xml = XDocument.Load(xmlPath);
            var configs = xml.Element("configuration").Element("appSettings");
            var temp = (from p in configs.Elements("add") where p.Attribute("key").Value == key select p).First().Attribute("value").Value.ToString();


            if (!bool.TryParse(temp, out value))
                throw new ArithmeticException("获取配置信息(" + key + "),原因：转型失敗!");

        }
        catch (Exception ex)
        {

            throw new ArgumentException("获取配置信息(" + key + "),原因：" + ex.Message + "!");

        }
        return value;
    }
    #endregion
    public static void SaveConfigValue(string key, string value, string fileName)
    {

        if (string.IsNullOrEmpty(key))
            throw new ArgumentNullException("获取配置信息(" + key + "),原因：传入的key为空!");
        string xmlPath = AppDomain.CurrentDomain.BaseDirectory + @"Configs\";
        if (string.IsNullOrEmpty(fileName))
            xmlPath += "SiteInfo";
        else
            xmlPath += fileName;
        xmlPath += ".config";


        try
        {
            XDocument xml = xml = XDocument.Load(xmlPath);
            var configs = xml.Element("configuration").Element("appSettings");
            var result = from p in configs.Elements("add") where p.Attribute("key").Value == key select p;
            result.First().Attribute("value").Value = value;
            xml.Save(xmlPath);


        }
        catch (Exception ex)
        {

            throw new ArgumentException("获取配置信息(" + key + "),原因：" + ex.Message + "!");

        }

    }
    public static void SaveConfigValue(string key, string value)
    {

        if (string.IsNullOrEmpty(key))
            throw new ArgumentNullException("获取配置信息(" + key + "),原因：传入的key为空!");
        string xmlPath = AppDomain.CurrentDomain.BaseDirectory + @"Configs\SiteInfo.config";



        try
        {
            XDocument xml = xml = XDocument.Load(xmlPath);
            var configs = xml.Element("configuration").Element("appSettings");
            var result = from p in configs.Elements("add") where p.Attribute("key").Value == key select p;
            result.First().Attribute("value").Value = value;
            xml.Save(xmlPath);


        }
        catch (Exception ex)
        {

            throw new ArgumentException("获取配置信息(" + key + "),原因：" + ex.Message + "!");

        }

    }

    /// <summary>
    /// 讀取HTML文件
    /// </summary>
    /// <param name="context"></param>
    public string LoadHtml(HttpContext context, string Encoding, string path)
    {
        System.IO.StreamReader reder = null;
        if (!"".Equals(path)&&new FileInfo(path).Exists)
        {
            try
            {
                context.Response.ContentType = "text/html";
                System.Text.Encoding code = System.Text.Encoding.UTF8;
                string filepath = path;
                reder = new System.IO.StreamReader(filepath, code);
                string htmls = reder.ReadToEnd();
                return htmls;
            }
            catch (Exception e)
            {

                return "讀取文件出錯:"+e;
            }
            finally
            {
                if (reder!=null&&reder.EndOfStream)
                    reder.Close();
            }
        }
        else
        {
            return "";
        }
    }
    /// <summary>
    /// 寫入HTML文件
    /// </summary>
    /// <param name="sb"></param>
    /// <param name="Encoding"></param>
    /// <param name="path"></param>
    /// <returns></returns>
    public bool WriteHtml(HttpContext context, StringBuilder sb, System.Text.Encoding Encoding, string path)
    {
        if (!"".Equals(path))
        {
            FileInfo fi=new FileInfo(path);
            if (!fi.Exists)
            {
                fi.Create();
            }
            //写入文本   
            StreamWriter sr = new StreamWriter(path, false, Encoding);
            try
            {
                sr.Write(sb.ToString());
                sr.Flush();
                return true;
            }
            catch (Exception)
            {

                return false;
            }
            finally
            {
                sr.Close();
            }
        }
        else
        {
            return false;
        }
    }
}
